package com.jobsys.controller;

import java.util.List;

import javax.servlet.http.Cookie;

import org.quartz.JobKey;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jobsys.dbprocess.Dbjob;
import com.jobsys.interceptor.VerifyManagerInterceptor;
import com.jobsys.model.MJobinfo;
import com.jobsys.model.MUserinfo;
import com.jobsys.model.Task;
import com.jobsys.quartz.QuartzPlugin;

@Before(VerifyManagerInterceptor.class)
public class ManagerController extends Controller {
	public void index() {
		// render("/jobsys/jobpage.jsp");
		// redirect("/jobpage.jsp");
		Cookie right = getCookieObject("right");
		String rightV = right.getValue();

		if (null == rightV || !rightV.equals("3")) {
			render("/jobpage.jsp");
		} else {
			render("/managerCenter.jsp");
		}
	}

	/**
	 * 查询所有用户
	 */
	@SuppressWarnings("unused")
	public void queryAllUser() {
		String page = this.getPara("pageNumber");
		String pagesize = this.getPara("pageSize");
		List<MUserinfo> userinfo = MUserinfo.dao.findAll(Integer.parseInt(page), Integer.parseInt(pagesize));
		int count = MUserinfo.dao.Count();

		JSONObject json = new JSONObject();
		json.put("rows", userinfo);
		json.put("total", count);

		renderJson(json);
	}

	// 修改用户信息
	public void updateUserinfo() {
		try {
			String id = this.getPara("id");
			String userid = this.getPara("userid");
			String pwd = this.getPara("pwd");
			String nickname = this.getPara("nickname");
			String right = this.getPara("rightx");
			String isdelete = this.getPara("isdelete");

			String re = "";

			MUserinfo userinfo = MUserinfo.dao.findByUserID(userid);

			if (null == userinfo) {
				re = "用户不存在！";
			} else {
				if (null == right || "" == right) {
					right = userinfo.getStr("right");
				}

				MUserinfo.dao.updateState(Integer.parseInt(id), userid, nickname, pwd, Integer.parseInt(right),
						Integer.parseInt(isdelete));
				re = "更新成功！";
			}

			JSONObject json = new JSONObject();
			json.put("msg", re);

			this.renderJson(json);
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	// 查询任务
	public void queryAllTask() {
		String page = this.getPara("pageNumber");
		String pagesize = this.getPara("pageSize");
		List<Task> tasks = Task.dao.findAll(Integer.parseInt(page), Integer.parseInt(pagesize));
		int count = Task.dao.Count();

		JSONObject json = new JSONObject();
		json.put("rows", tasks);
		json.put("total", count);

		renderJson(json);
	}

	// 修改任务
	public void updateTask() {
		try {
			int id = this.getParaToInt("id");
			String exp = this.getPara("exp");
			int state = this.getParaToInt("state");
			String name = this.getPara("name");
			String info = this.getPara("info");

			boolean isRight = org.quartz.CronExpression.isValidExpression(exp);
			String re = "";
			if (isRight) {
				// 启动或重新启动或停止该任务
				restartTask(id, state, exp);

				// 更新
				Task.dao.updateTask(id, exp, state, name, info);

				re = "更新成功！";
			} else {
				re = "表达式错误";
			}

			JSONObject json = new JSONObject();
			json.put("msg", re);

			this.renderJson(json);
		} catch (Exception ex) {
			System.out.println(ex);
			this.render("./except.html");
		}
	}

	// 初始化用户cookie，可以考虑js直接完成
	public void init() {
		JSONObject userinfo = new JSONObject();
		String userID = this.getCookie("userID");
		userinfo.put("userID", userID);

		String right = this.getCookie("right");
		userinfo.put("right", right);

		renderJson(userinfo);
	}

	// 统计信息汇总
	public void countAll() {
		List<MJobinfo> re = Dbjob.CountAll();
		renderJson(re);
	}

	// 任务启动或关闭，或重启
	private void restartTask(int id, int newState, String exp) {
		Task task = Task.dao.findById(id);
		int state = task.getInt("state");
		if (newState == 0 && state == 0) {
			return;
		}

		try {
			String className = task.getStr("clazz");

			JobKey jobKey = JobKey.jobKey(className, className);
			if (newState == 0 && state == 1) {
				QuartzPlugin.scheduler.pauseJob(jobKey); // 暂停任务
				System.out.println("暂停任务" + id);
			} else if (newState == 1 && state == 0) {
				QuartzPlugin.scheduler.resumeJob(jobKey); // 恢复任务
				System.out.println("恢复任务" + id);
			} else if (newState == 1 && state == 1 && !exp.equals(task.getStr("exp"))) {
				QuartzPlugin.scheduler.pauseJob(jobKey); // 暂停任务
				QuartzPlugin.scheduler.resumeJob(jobKey); // 恢复任务
				System.out.println("重启任务" + id);
			}

			// Task.dao.updateState(id, Task.STATE_START);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}
}
